package com.jt.common.Thread;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * 简易服务注册中心测试(基于此,思考Nacos中服务的注册和发现)
 * 1)测试服务的注册
 * 2)测试服务的发现
 */
public class RegistryTests {
    //存储服务信息的容器(可以简单理解为nacos中存储服务信息的对象)
    private static Map<String,String> registryMap=new HashMap<>(3);
    //private static Map<String,String> registryMap=new ConcurrentHashMap<>();
    //private static final ReentrantReadWriteLock readWriteLock = new ReentrantReadWriteLock();
    //服务的注册,将服务信息存储到map
    public  static void doRegist(String serviceId,String host){//悲观写
        //  readWriteLock.writeLock().lock();
        try {
            registryMap.put(serviceId, host);
        }finally {
            //  readWriteLock.writeLock().unlock();
        }
    }
    //服务的发现,从map中基于key获取服务实例
    public  static String doLookup(String serviceId){//乐观读
        // readWriteLock.readLock().lock();
        try {
            return registryMap.get(serviceId);
        }finally {
            // readWriteLock.readLock().unlock();
        }
    }
    public static void main(String[] args) {
        //1.构建服务名,服务地址,服务名与服务地址有一一对应关系
        //1.1服务名
        String[] serviceIds=new String[10000];
        //1.2服务地址
        String[] hostIds=new String[10000];
        //1.3数据初始化
        for(int i=0;i<10000;i++){
            serviceIds[i]="Serivce-"+i;
            hostIds[i]="Host-"+i;
        }
        //2.构建线程对象,模拟服务注册和发现
        Thread t1=new Thread(){
            @Override
            public void run() {
                for(int i=0;i<10000;i++){
                    doRegist(serviceIds[i],hostIds[i]);
                }
            }
        };
        //2.构建线程对象,模拟服务注册和发现
        Thread t2=new Thread(){
            @Override
            public void run() {
                for(int i=0;i<100;i++){
                    System.out.println(serviceIds[i]+":"+doLookup(serviceIds[i]));
                }
            }
        };
        Thread t3=new Thread(){
            @Override
            public void run() {
                for(int i=0;i<100;i++){
                    registryMap.remove(serviceIds[i]);
                    try{Thread.sleep(100);}catch (Exception e){}
                }
            }
        };
        t1.start();
        t2.start();
        t3.start();


    }
}
